//
//  StringEx.swift
//
//
//  Created by S JZ on 2024/8/30.
//

import Foundation

extension BasicWrapper where Base == String {
    // 转为NSString
    public var nsString: NSString { return self.base as NSString }
    
    // MARK: - 将字符串转为字符型
    public var doubleValue: Double { nsString.doubleValue }
    
    public var floatValue: Float { nsString.floatValue }
    
    public var intValue: Int { nsString.integerValue }
    
    public var boolValue: Bool { nsString.boolValue }
    
    public var CGFloatValue: CGFloat { CGFloat(floatValue) }
    
    // MARK: - 获取子字符串，通过转为NSString
    @discardableResult
    public func subString(form: Int) -> String {
        guard self.base.count > form else { return "" }
        return self.nsString.substring(from: form)
    }
    
    @discardableResult
    public func subString(to: Int) -> String {
        guard self.base.count > to else { return "" }
        return self.nsString.substring(to: to)
    }
    
    @discardableResult
    public func subString(with range: NSRange) -> String {
        guard self.base.count > range.upperBound, range.lowerBound >= 0 else { return "" }
        return nsString.substring(with: range)
    }
    
    // MARK: - 下标
    public subscript(bounds: CountableRange<Int>) -> String {
        guard self.base.count > bounds.upperBound, bounds.lowerBound >= 0 else { return "" }
        let start = self.base.index(self.base.startIndex, offsetBy: bounds.lowerBound) //index(startIndex, offsetBy: bounds.lowerBound)
        let end = self.base.index(self.base.startIndex, offsetBy: bounds.upperBound)
        let str = self.base[start..<end]
        return String(str)
    }
    
    public subscript(bounds: CountableClosedRange<Int>) -> String {
        guard self.base.count > bounds.upperBound, bounds.lowerBound >= 0 else { return "" }
        let start = self.base.index(self.base.startIndex, offsetBy: bounds.lowerBound)
        let end = self.base.index(self.base.startIndex, offsetBy: bounds.upperBound)
        let str = self.base[start...end]
        return String(str)
    }
    
    public subscript(index: Int) -> String {
        guard self.base.count > index else { return "" }
        let character = self.base[self.base.index(self.base.startIndex, offsetBy: index)]
        return String(character)
    }
}
